package com.learning.security.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.learning.security.api.AdminOAuth2TokenApi;
import com.learning.security.core.DefaultSecurityMetadataSource;
import com.learning.security.core.filter.TokenAuthenticationFilter;
import com.learning.security.service.AdminRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.http.HttpStatus;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.ObjectPostProcessor;
import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.annotation.web.configurers.UrlAuthorizationConfigurer;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.security.web.access.intercept.FilterSecurityInterceptor;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

@EnableMethodSecurity
public class WebSecurityConfigurerAdapterLab extends WebSecurityConfigurerAdapter {
    @Autowired
    private AdminOAuth2TokenApi adminOAuth2TokenApi;

    @Autowired
    private AdminRoleService adminRoleService;

    @Autowired
    private DefaultSecurityMetadataSource defaultSecurityMetadataSource;

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        ApplicationContext applicationContext = http.getSharedObject(ApplicationContext.class);
        http.apply(new UrlAuthorizationConfigurer<>(applicationContext))
                .withObjectPostProcessor(objectPostProcessor());

        http.cors().configurationSource(configurationSource()).and() // 开启跨域
                .csrf().disable()
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()
                .headers().frameOptions().disable().and()
                .exceptionHandling().authenticationEntryPoint(authenticationEntryPoint())
                .accessDeniedHandler(accessDeniedHandler()).and()
                .authorizeRequests()
                .mvcMatchers("/admin/system/login").permitAll()
                .mvcMatchers("/admin/user/create").permitAll()
                .anyRequest().authenticated()
        ;

        http.addFilterBefore(new TokenAuthenticationFilter(adminOAuth2TokenApi, adminRoleService), UsernamePasswordAuthenticationFilter.class);
    }

    private static AuthenticationEntryPoint authenticationEntryPoint() {
        return (request, response, authException) -> {
            Map<String, Object> result = new HashMap<String, Object>();
            result.put("msg", "请先登录"+ authException.getMessage());// 打印登录成功信息
            result.put("code", 200);// 打印状态码   此处改为setStatus
            response.setContentType("application/json;charset=UTF-8");// 设置响应类型
            response.setStatus(HttpStatus.UNAUTHORIZED.value());
            String s = new ObjectMapper().writeValueAsString(result);// json格式转字符串
            response.getWriter().println(s);// 打印json格式数据
        };
    }

    private static AccessDeniedHandler accessDeniedHandler() {
        return (request, response, e) -> { // 处理授权异常
            response.setContentType("application/json;charset=UTF-8");
            response.setStatus(HttpStatus.FORBIDDEN.value());
            response.getWriter().write("无权访问!" + e.getMessage());
        };
    }

    private CorsConfigurationSource configurationSource() {
        CorsConfiguration corsConfiguration = new CorsConfiguration();
        corsConfiguration.setAllowedHeaders(Arrays.asList("*"));
        corsConfiguration.setAllowedMethods(Arrays.asList("*"));
        corsConfiguration.setAllowedOrigins(Arrays.asList("*"));
        corsConfiguration.setMaxAge(3600L);
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", corsConfiguration);
        return source;
    }

    private ObjectPostProcessor<FilterSecurityInterceptor> objectPostProcessor() {
        return new ObjectPostProcessor<FilterSecurityInterceptor>() {
            @Override
            public <O extends FilterSecurityInterceptor> O postProcess(O object) {
                object.setSecurityMetadataSource(defaultSecurityMetadataSource);
                object.setRejectPublicInvocations(false);
                return object;
            }
        };
    }
}